package 队列;

import java.util.Iterator;

public class LinkedListQueue <E>implements Queue<E>,Iterable<E>{
private static class Node<E> {//基本框架
    E value;
    Node<E> next;

    public Node(E value, Node<E> next) {
        this.next = next;
        this.value = value;
    }
}
Node<E>head=new Node<>(null,null);
Node<E>tail=head;
public int size;
private int capacity=Integer.MAX_VALUE;
    {
        tail.next=head;
    }
    public LinkedListQueue(int capacity){
        this.capacity=capacity;
    }
    public LinkedListQueue(){

    }



    @Override
    public Iterator<E> iterator() {//迭代器遍历
       return new Iterator<E>() {
           Node<E> p=head.next;
           @Override
           public boolean hasNext() {//判断是否往下进行
               return p!=head;
           }

           @Override
           public E next() {//往下进行返回值
               E value=p.value;
               p=p.next;
               return value;
           }
       };
    }

    @Override
    public boolean offer(E value) {//尾插法
        if(size==capacity){
            return false;
        }
        Node<E> added=new Node<>(value,head);//创建在最尾部
        tail.next=added;
        tail=added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if(isEmpty()){
            return null;
        }
        E value=head.next.value;
        head.next=head.next.next;
        return value;
    }

    @Override
    public E peek() {//拿出下一个值
        if(isEmpty()){
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
       return head==tail;
    }
}
